package com.ali.sso.common.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;

import com.ali.sso.common.model.UserLogin;
import com.ali.sso.common.service.IOAuthService;

public class UserLoginRealm extends DistributedAuthorizingRealm {
	
	private IOAuthService oauthService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userLoginId = (String)principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//根据userLoginId加载权限，并设置在authorizationInfo中
		//应该把权限信息存在分布式缓存中
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userLoginId = (String)token.getPrincipal();
		UserLogin userLogin = oauthService.findUserLogin(userLoginId);
		if(userLogin == null) 
			throw new UnknownAccountException();
		
		//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userLogin.getUserLoginId(), userLogin.getPassword(), getName());
        return authenticationInfo;
	}

	public IOAuthService getOauthService() {
		return oauthService;
	}
	public void setOauthService(IOAuthService oauthService) {
		this.oauthService = oauthService;
	}
	
}
